package com.smyx.case1;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

@Slf4j
public class DistributeServer {

    private static final String CONNECTION_STRING = "vm110:2181,vm111:2181,vm112:2181";
    private static final int SESSION_TIME = 2000;
    private static final String PARENT_NODE = "/servers";
    private ZooKeeper zkClient = null;

    /**
     * 获取zk客户端连接
     */
    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(CONNECTION_STRING, SESSION_TIME, watchedEvent -> {
            log.info(">>>>>>>>>>>>>>>> server watchedEvent........");
        });
    }

    private void registerServer(String hostname) throws InterruptedException, KeeperException {
        String create = zkClient.create(PARENT_NODE + "/server",
                hostname.getBytes(), // 服务名称
                /*
                 * OPEN_ACL_UNSAFE：完全开放的ACL，任何连接的客户端都可以操作该属性znode
                 * CREATOR_ALL_ACL：只有创建者才有ACL权限
                 * READ_ACL_UNSAFE：只能读取ACL
                 */
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                /*
                 * Zookeeper中有四种CreateMode，分为两类，持久化节点和临时节点，自动编号节点和非自动编号节点
                 * PERSISTENT                持久化节点
                 * PERSISTENT_SEQUENTIAL     顺序自动编号持久化节点，这种节点会根据当前已存在的节点数自动加 1
                 * EPHEMERAL                 临时节点， 客户端session超时这类节点就会被自动删除
                 * EPHEMERAL_SEQUENTIAL      临时自动编号节点
                 */
                CreateMode.EPHEMERAL_SEQUENTIAL); // 临时是
        log.info(hostname + " is online " + create);
    }

    private void business(String hostname) throws InterruptedException {
        System.out.println(hostname + " is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        String hostname = "vm110";
        // 1 获取 zk 连接
        DistributeServer server = new DistributeServer();
        server.getConnect();
        // 2 利用 zk 连接注册服务器信息
        server.registerServer(hostname);
        // 3 启动业务功能
        server.business(hostname);
    }

}
